package com.fh.modules.ss.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fh.common.api.vo.Result;
import com.fh.common.aspect.annotation.AutoLog;
import com.fh.common.constant.CommonConstant;
import com.fh.common.query.QueryWrapperUtil;
import com.fh.common.util.ConvertUtils;
import com.fh.modules.ss.entity.SsMaterialInst;
import com.fh.modules.ss.service.ISsMaterialInstService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * @Title: Controller
 * @Description: 物料实例
 * @author： code generator
 * @date： 2019-09-09
 * @version： V1.0
 */
@RestController
@RequestMapping("/ss/ssMaterialInst")
@Slf4j
@Api("物料实例")
public class SsMaterialInstController {
    @Autowired
    private ISsMaterialInstService ssMaterialInstService;

    /**
     * 分页列表查询
     *
     * @param ssMaterialInst
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @ApiOperation("分页列表查询")
    @AutoLog(value = "物料实例分页查询", logType = CommonConstant.LOG_TYPE_QUERY)
    public Result queryPageList(SsMaterialInst ssMaterialInst,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        QueryWrapper<SsMaterialInst> queryWrapper = new QueryWrapper<SsMaterialInst>();
        ssMaterialInst.setDelFlag(CommonConstant.DEL_FLAG_0);
        QueryWrapperUtil.initQueryWrapper(queryWrapper, ssMaterialInst);
        Page<SsMaterialInst> page = new Page<SsMaterialInst>(pageNo, pageSize);
        IPage<SsMaterialInst> pageList = ssMaterialInstService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param ssMaterialInst
     * @return
     */
    @PostMapping(value = "/add")
    @ApiOperation("添加")
    @AutoLog("添加物料实例")
    public Result add(@RequestBody SsMaterialInst ssMaterialInst) {
        ssMaterialInst.setDelFlag(CommonConstant.DEL_FLAG_0);
        ssMaterialInstService.save(ssMaterialInst);
        return Result.ok("添加成功");
    }

    /**
     * 编辑
     *
     * @param ssMaterialInst
     * @return
     */
    @PutMapping(value = "/edit")
    @ApiOperation("修改")
    @AutoLog("修改物料实例")
    public Result edit(@RequestBody SsMaterialInst ssMaterialInst) {
        boolean ok = ssMaterialInstService.updateById(ssMaterialInst);
        return ok ? Result.ok("修改成功") : Result.error("修改失败");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    @ApiOperation("通过id删除")
    @AutoLog("删除物料实例")
    public Result delete(@RequestParam(name = "id", required = true) String id) {
        ssMaterialInstService.deleteEntityByDelFlag(id);
        return Result.ok("删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    @ApiOperation("批量删除")
    @AutoLog("批量删除物料实例")
    public Result deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        ssMaterialInstService.deleteBatchEntityByDelFlag(ids);
        return Result.ok("批量删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation("通过id查询")
    @AutoLog(value = "物料实例通过id查询", logType = CommonConstant.LOG_TYPE_QUERY)
    public Result queryById(@RequestParam(name = "id", required = true) String id) {
        SsMaterialInst ssMaterialInst = ssMaterialInstService.getById(id);
        return Result.ok(ssMaterialInst);
    }

    @GetMapping(value = "/queryMaterialTree")
    @ApiOperation("查询物料资源树")
    @AutoLog(value = "查询物料资源树", logType = CommonConstant.LOG_TYPE_QUERY)
    public Result queryMaterialTree() {
        return Result.ok(ssMaterialInstService.convert());
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    @ApiOperation("导出excel")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<SsMaterialInst> queryWrapper = new QueryWrapper<SsMaterialInst>();
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (ConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                SsMaterialInst ssMaterialInst = JSON.parseObject(deString, SsMaterialInst.class);
                QueryWrapperUtil.initQueryWrapper(queryWrapper, ssMaterialInst);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SsMaterialInst> pageList = ssMaterialInstService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "物料实例列表");
        mv.addObject(NormalExcelConstants.CLASS, SsMaterialInst.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("物料实例列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ApiOperation("通过excel导入")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SsMaterialInst> listSsMaterialInsts = ExcelImportUtil.importExcel(file.getInputStream(), SsMaterialInst.class, params);
                for (SsMaterialInst ssMaterialInstExcel : listSsMaterialInsts) {
                    ssMaterialInstService.save(ssMaterialInstExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listSsMaterialInsts.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

}
